<template>
  <div ref="container" class="model-fullscreen"></div>
</template>


<script>
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

export default {
  name: 'ModelViewer',
  mounted() {
    const container = this.$refs.container

    const scene = new THREE.Scene()
    const camera = new THREE.PerspectiveCamera(
      75,
      container.clientWidth / container.clientHeight,
      0.1,
      1000
    )

    const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true })
    renderer.setSize(container.clientWidth, container.clientHeight)
    container.appendChild(renderer.domElement)

    const ambientLight = new THREE.AmbientLight(0xffffff, 1)
    scene.add(ambientLight)

    const controls = new OrbitControls(camera, renderer.domElement)
    controls.enableDamping = true

    const loader = new GLTFLoader()

    let pivot = null

    loader.load('/ford_raptor/scene.gltf', (gltf) => {
      const model = gltf.scene
      model.scale.set(0.05, 0.05, 0.05)

      // 居中模型
      const box = new THREE.Box3().setFromObject(model)
      const size = new THREE.Vector3()
      const center = box.getCenter(new THREE.Vector3())
      box.getSize(size)
      model.position.set(-center.x, -center.y + size.y / 2, -center.z)

      // 用 Group 包一层，方便自转
      pivot = new THREE.Group()
      pivot.add(model)
      scene.add(pivot)

      // OrbitControls 目标点设置为模型中心
      controls.target.set(0, size.y / 2, 0)
      controls.update()

      // 设置相机位置并对准模型
      camera.position.set(0, size.y * 0.6, -size.z * 2.5)
      camera.lookAt(0, size.y / 2, 0)
    })

    const animate = () => {
      requestAnimationFrame(animate)
      if (pivot) {
        pivot.rotation.y += 0.01
      }
      controls.update()
      renderer.render(scene, camera)
    }

    animate()
    

    window.addEventListener('resize', () => {
      const width = container.clientWidth
      const height = container.clientHeight
      camera.aspect = width / height
      camera.updateProjectionMatrix()
      renderer.setSize(width, height)
    })
  },
}
</script>

<style scoped>
.model-fullscreen {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  z-index: 0;
  pointer-events: auto;
}
</style>



